package shuzu

import (
	"bufio"
	"fmt"
	"math"
	"os"
	"sort"
	"strconv"
	"strings"
)

func ParseArea() {
	scanner := bufio.NewScanner(os.Stdin)
	scanner.Scan()
	text := scanner.Text()
	fields := strings.Fields(text)
	a, _ := strconv.Atoi(fields[0])
	b, _ := strconv.Atoi(fields[1])
	nums := make([][]int, 0)
	for i := 0; i < a; i++ {
		scanner.Scan()
		inner := make([]int, b)
		num := strings.Fields(scanner.Text())
		if len(num) == 0 {
			break
		}
		for i := 0; i < b; i++ {
			inner[i], _ = strconv.Atoi(num[i])
		}
		nums = append(nums, inner)
	}
	fmt.Println(work2(nums))
}

func work2(nums [][]int) int {
	// 进行行列计算：先算所有，然后减去使用的行或列
	ans := sum1(nums)
	count := math.MaxInt32
	// 行
	if len(nums) != 1 {
		for i := 0; i < len(nums)-1; i++ {
			num := sum2(nums, i)
			fmt.Println("row", ans-2*num, num)
			if count > abs1(ans-2*num) {
				count = abs1(ans - 2*num)
			}
		}
	}
	// 列
	if len(nums[0])-1 != 0 {
		for i := 0; i < len(nums[i])-1; i++ {
			num := sum3(nums, i)
			fmt.Println("col", ans-2*num, num)
			if count > abs1(ans-2*num) {
				count = abs1(ans - 2*num)
			}
		}
	}
	if count == math.MaxInt32 {
		return 0
	}
	return count
}

func sum2(nums [][]int, row int) (ans int) {
	for i := 0; i <= row; i++ {
		for j := 0; j < len(nums[i]); j++ {
			ans += nums[i][j]
		}
	}
	return
}

func sum3(nums [][]int, col int) (ans int) {
	for i := 0; i <= col; i++ {
		for j := 0; j < len(nums); j++ {
			ans += nums[j][i]
		}
	}
	return
}

func sum1(nums [][]int) (ans int) {
	for i := 0; i < len(nums); i++ {
		for j := 0; j < len(nums[i]); j++ {
			ans += nums[i][j]
		}
	}
	return
}

func abs1(num int) int {
	if num < 0 {
		return -1 * num
	}
	return num
}

func work1(nums []int) {
	// 先sort降序，然后依次增加，最后相减
	sort.Slice(nums, func(i, j int) bool {
		return nums[i] > nums[j]
	})
	fmt.Println(nums)
	left, right := 0, 0
	for i := 0; i < len(nums); i++ {
		if left > right {
			right += nums[i]
		} else {
			left += nums[i]
		}
	}
	if left > right {
		fmt.Println(left - right)
	} else {
		fmt.Println(right - left)
	}
}
